package com.wdciti.sccp.iot.springvertx.protocols.mqtt;

import io.netty.handler.codec.mqtt.MqttQoS;
import io.vertx.core.MultiMap;
import io.vertx.mqtt.messages.MqttPublishMessage;
import lombok.Data;

/**
 * @author JINWEN
 */
@Data
public class MqttHeader {

    private int msgId;
    /**
     * Quality of service level
     */
    private MqttQoS qosLevel;

    /**
     * If the message is a duplicate
     */
    private boolean isDup;

    /**
     * If the message needs to be retained
     */
    private boolean isRetain;

    /**
     * Topic on which the message was published
     */
    private String topicName;

    /**
     * Payload  Data Type , support json till now.
     */
    private String codec = "json";

    public MqttHeader() {
    }
    public MqttHeader(MqttQoS qosLevel, boolean isDup, boolean isRetain) {
        this.qosLevel = qosLevel;
        this.isDup = isDup;
        this.isRetain = isRetain;
    }

    public MqttHeader(MqttQoS qosLevel, boolean isDup, boolean isRetain,String topicName) {
        this.qosLevel = qosLevel;
        this.isDup = isDup;
        this.isRetain = isRetain;
        this.topicName = topicName;
    }

    public MultiMap addMqttHeader(MultiMap header) {
        if (header == null) {
            header = MultiMap.caseInsensitiveMultiMap();
        }
        header.add("topic", this.getTopicName())
                .add("qos", String.valueOf(this.getQosLevel().value()))
                .add("isDup", String.valueOf(this.isRetain()))
                .add("isRetain", String.valueOf(this.isDup()));
        return header;
    }

    public static MqttHeader buildFrom(MqttPublishMessage message) {
        MqttHeader mqttHeader = new MqttHeader();
        if (message != null) {
            mqttHeader.setTopicName(message.topicName());
            mqttHeader.setDup(message.isDup());
            mqttHeader.setRetain(message.isRetain());
            mqttHeader.setQosLevel(message.qosLevel());
            mqttHeader.setMsgId(message.messageId());
        }
        return mqttHeader;
    }

    public static MqttHeader buildFrom(MultiMap header) {
        MqttHeader mqttHeader = new MqttHeader();
        mqttHeader.setTopicName(header.get("topic"));
        mqttHeader.setDup(Boolean.parseBoolean(header.get("isDup")));
        mqttHeader.setRetain(Boolean.parseBoolean(header.get("isRetain")));
        mqttHeader.setQosLevel(MqttQoS.valueOf(Integer.parseInt(header.get("qos"))));
        if (header.contains("msgId")) {
            mqttHeader.setMsgId(Integer.parseInt(header.get("msgId")));
        }
        return mqttHeader;
    }
}
